package com.hymjweb.demo.hymj.system_maintenance.role.service;

import com.github.pagehelper.PageInfo;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.system_maintenance.role.bean.RolePojo;
import com.hymjweb.demo.hymj.system_maintenance.role.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class RoleService extends BaseService {

    @Autowired
    private RoleMapper roleMapper;

    public Object getPageList(Map param) {
        // 分页初始化
        this.pageListInit(param);
        List<RolePojo> list = getRoleListNoPage(param);
        PageInfo pageInfo = new PageInfo(list);
        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }

    private List<RolePojo> getRoleListNoPage(Map param) {
        return roleMapper.queryByCnd(param);
    }

    /**
     * 根据 角色 ID获取角色对象
     *
     * @param roleId
     * @return
     */
    public RolePojo getRolePojoById(String roleId) {
        if (DataTypeUtil.isEmptyStr(roleId)) {
            return null;
        }
        return roleMapper.getRolePojoById(roleId);
    }

    /**
     * 根据 ids 获取角色列表,格式为 'id1','id2'
     *
     * @param userRoleIds
     * @return
     */
    public List<RolePojo> getRolePojoByIds(String userRoleIds) {
        if (DataTypeUtil.isEmptyStr(userRoleIds)) {
            return null;
        }
        return roleMapper.getRolePojoByIds(userRoleIds);
    }


    /**
     * 根据角色名称检测角色对象
     *
     * @param name
     * @return
     */
    public RolePojo checkNameUnique(String name) {
        return roleMapper.checkNameUnique(name);
    }

    /**
     * 添加角色对象
     *
     * @param rolePojo
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int addRole(RolePojo rolePojo) throws Exception {
        if (rolePojo == null) {
            throwException("角色添加参数错误!");
        }

        // 1.检测名称是否重复
        RolePojo pojo = checkNameUnique(rolePojo.getName());

        if (pojo != null) {
            throwException("角色添加角色名称重复!");
        }

        rolePojo.setId(this.getSysStrId());

        return roleMapper.insert(rolePojo);
    }

    /**
     * 更新角色对象
     *
     * @param rolePojo
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int updateRole(RolePojo rolePojo) throws Exception {
        if (rolePojo == null) {
            throwException("角色更新参数错误!");
        }

        return roleMapper.update(rolePojo);
    }


}
